import { Fragment, type FC } from "react";
import {
  componentConfGroup,
  ComponentConfType,
} from "@/components/QuestionComponents";
import { Typography } from "antd";
import { cn } from "@/utils/core-uitls";
import { useDispatch } from "react-redux";
import { addComponent } from "@/store/componentReducer";
import { nanoid } from "nanoid";
const { Title } = Typography;

function useGetComponent() {
  const dispatch = useDispatch();

  function handleClick(c: ComponentConfType) {
    const { title, type, defaultProps } = c;
    dispatch(
      addComponent({
        title,
        type,
        props: defaultProps,
        fe_id: nanoid(),
      })
    );
  }

  const Comp = (c: ComponentConfType) => {
    const { Component } = c;
    return (
      <div
        className=" mb-3 cursor-pointer bg-gray-100 border-1 border-white p-3 rounded-md  hover:shadow-lg hover:shadow-blue-300/5 hover:border-[#d9d9d9] pointer-events-nones"
        onClick={() => handleClick(c)}
      >
        <div className="pointer-events-none">
          <Component />
        </div>
      </div>
    );
  };
  return Comp;
}

const CompponentLib: FC = () => {
  const getComponent = useGetComponent();
  return (
    <div>
      {componentConfGroup.map((group, index) => {
        const { groupName, components } = group;
        return (
          <div key={index}>
            <Title
              level={3}
              className={cn({ "mt-6": index > 0 }, "!text-base")}
            >
              {groupName}
              <div>
                {components.map((c, index) => {
                  return <Fragment key={index}>{getComponent(c)}</Fragment>;
                })}
              </div>
            </Title>
          </div>
        );
      })}
    </div>
  );
};

export default CompponentLib;
